package com.lqg.bookLibrary.common.securityImpl;

import com.alibaba.fastjson2.JSON;
import com.lqg.bookLibrary.common.core.domain.JsonResult;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录失败逻辑处理
 * */
@Component
public class AuthenticationFailureHandlerImpl implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        JsonResult jsonResult = null;
        if(e instanceof UsernameNotFoundException){
            String msg=e.toString();
            jsonResult = JsonResult.error(msg);
        }else if(e instanceof BadCredentialsException){
            jsonResult = JsonResult.error("密码错误");
        }else if (e instanceof InternalAuthenticationServiceException){
            jsonResult = JsonResult.error("用户不存在");
        }
        //处理编码方式，防止中文乱码的情况
        httpServletResponse.setContentType("text/json;charset=utf-8");
        //塞到HttpServletResponse中返回给前台
        String output= JSON.toJSONString(jsonResult);
        httpServletResponse.getWriter().write(output);
    }
}
